package com.agent.common.utils;

import com.agent.common.entity.UserContext;
import com.agent.common.exception.AuthenticationException;
import com.agent.common.result.ResultCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息提取工具类
 */
public class TokenInfoUtils {

    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";

    /**
     * 从当前请求获取用户上下文
     */
    public static UserContext getCurrentUser(JwtUtils jwtUtils) {
        HttpServletRequest request = ((ServletRequestAttributes) 
            RequestContextHolder.currentRequestAttributes()).getRequest();
        return extractUserFromRequest(request, jwtUtils);
    }

    /**
     * 从请求中提取用户信息
     */
    public static UserContext extractUserFromRequest(
        HttpServletRequest request, 
        JwtUtils jwtUtils
    ) {
        String token = extractToken(request);
        if (token == null) return null;
        
        // 自动检测令牌类型（RSA/HMAC）
        boolean isRsaToken = token.length() > 150; // 简单启发式判断
        return jwtUtils.extractUserContext(token, isRsaToken);
    }

    private static String extractToken(HttpServletRequest request) {
        String header = request.getHeader(AUTH_HEADER);
        if (header != null && header.startsWith(BEARER_PREFIX)) {
            return header.substring(BEARER_PREFIX.length());
        }
        return null;
    }

    /**
     * 提取特定声明信息
     */
    public static <T> T extractClaim(
        HttpServletRequest request, 
        JwtUtils jwtUtils, 
        String claimName, 
        Class<T> valueType
    ) {
        String token = extractToken(request);
        if (token == null) return null;
        
        boolean isRsaToken = token.length() > 150;
        return jwtUtils.extractClaim(token, isRsaToken, claimName, valueType);
    }

    /**
     * 从令牌中提取用户上下文
     * @param token JWT令牌
     * @param jwtUtils JWT工具实例
     * @return 用户上下文
     */
    public static UserContext extractUserContextFromToken(String token, JwtUtils jwtUtils) {
        // 自动检测令牌类型（RSA/HMAC）
        boolean isRsaToken = token.length() > 150; // 简单启发式判断

        try {
            return jwtUtils.extractUserContext(token, isRsaToken);
        } catch (Exception e) {
            throw new AuthenticationException(ResultCode.UNAUTHORIZED, "Failed to extract user context from token");
        }
    }

    /**
     * 从令牌中提取特定声明
     * @param token JWT令牌
     * @param jwtUtils JWT工具实例
     * @param claimName 声明名称
     * @param valueType 值类型
     * @return 声明值
     */
    public static <T> T extractClaimFromToken(String token, JwtUtils jwtUtils,
                                              String claimName, Class<T> valueType) {
        boolean isRsaToken = token.length() > 150;
        return jwtUtils.extractClaim(token, isRsaToken, claimName, valueType);
    }
}